<template>
  <div class="content-table list-page">
    <el-card class="minh100">
      <div class="list-h">
        <el-button
          type="primary"
          @click="dialogVisibleTransferAdd = true"
          v-auth="`/projectsA/team--add`"
          class="add-option"
          >添加</el-button
        >
      </div>

      <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
        <el-table
          :data="tableData"
          ref="tableRef"
          stripe
          v-loading="loading"
          :header-cell-style="{
            background: '#F7F9FD',
            color: '#000',
            height: '48px',
            borderTop: '1px soild #E4E8F2'
          }"
        >
          <template #empty>
            <el-empty :image-size="150" description="暂无数据"></el-empty>
          </template>
          <el-table-column type="index" label="序号" width="50">
            <template v-slot="scope">
              <span>{{
                (formInline.pageNum - 1) * formInline.pageSize +
                scope.$index +
                1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名">
            <template #default="{ row }">
              {{ row.userName && row.userName.split("(")[0] }}
            </template>
          </el-table-column>
          <el-table-column label="所属单位">
            <template #default="{ row }">
              <span class="text--info">{{ row.deptName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="phoneNum" label="手机号"></el-table-column>
          <el-table-column
            prop="proRoleName"
            label="项目组角色"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="createUserName"
            label="操作人"
          ></el-table-column>
          <el-table-column
            prop="createTime"
            label="操作时间"
            width="160"
          ></el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button
                type="text"
                @click="handleEdit(row)"
                v-auth="`/projectsA/team--edit`"
                >编辑</el-button
              >
              <el-button
                type="text"
                class="btns-danger"
                v-auth="`/projectsA/team--delete`"
                @click="showDeleteMessageBox(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-skeleton>
      <re-pagination
        :total="total"
        v-show="total > 0"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleSearch"
      />
    </el-card>
    <el-dialog
      title="编辑项目组成员"
      v-model="dialogFormVisible"
      destroy-on-close
      width="520px"
    >
      <user-detail
        @emitClose="emitClose"
        :userInfo="userInfo"
        :rolesList="roleTypeList"
      />
    </el-dialog>
    <el-dialog title="添加项目组成员" v-model="dialogVisibleTransferAdd">
      <add-user
        v-model:dialogVisibleTransferAdd="dialogVisibleTransferAdd"
        :currentUsers="acceptUsers"
        @emitAddUser="emitAddUser"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref, defineComponent } from "vue";
import { ElMessageBox } from "element-plus";
import UserDetail from "./UserDetail.vue";
import RePagination from "/@/components/RePagination/index.vue";
import NotifMessage from "/@/utils/message/notification";
import AddUser from "../../../projectsA/acceptance/concealed/components/dialog/AddUser.vue";
import {
  projectTeamList,
  addToProjectTeamList,
  delProjectTeam
} from "/@/api/projects";
import { postDictList } from "/@/api/home";
import { storageLocal } from "/@/utils/storage";

export default defineComponent({
  name: "UserManage",
  components: {
    UserDetail,
    RePagination,
    AddUser
  },

  setup() {
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const tableRef = ref<HTMLTableElement | null>(null) as any;
    let projectInfo = storageLocal.getItem("projectInfo");
    let loading = ref<boolean>(false);
    let total = ref<number>(0);
    let formInline = reactive({
      projectId: projectInfo?.id,
      sectionId: "A",
      pageNum: 1,
      pageSize: 10
    });
    let state = reactive({
      tableData: [],
      userInfo: {},
      dialogVisibleTransferAdd: false, // 添加成员弹窗是否显示
      dialogFormVisible: false, // 编辑成员弹窗是否显示
      acceptUsers: [] // 已选中的人员
    });
    let roleTypeList = ref([]);

    const emitAddUser = async user => {
      state.acceptUsers = user.infoList;
      state.dialogVisibleTransferAdd = false;
      let proUserList = [];
      state.acceptUsers.forEach(item => {
        let obj = {
          deptCode: item.deptCode,
          deptName: item.deptName,
          phoneNum: item.phoneNum,
          email: item.email,
          projectId: projectInfo?.id,
          projectName: projectInfo?.name,
          userId: item.id,
          userName: `${item.name}(${item.userName})`
        };
        proUserList.push(obj);
      });
      // 添加至成员
      let params = {
        proUserList,
        sectionId: "A"
      };
      await addToProjectTeamList(params);
      getTableData(formInline);
    };

    // 请求表格数据
    const getTableData = async (obj: object = {}) => {
      loading.value = true;
      try {
        const { code, data } = await projectTeamList(obj);
        if (code === 200) {
          state.tableData = data.list;
          total.value = data.rows;
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    };

    const emitClose = (isSubmit: boolean) => {
      state.dialogFormVisible = false;
      if (isSubmit) {
        formInline.pageNum = 1;
        getTableData(formInline);
      }
    };

    // 重置条件
    const handleReset = (): void => {
      formRef.value.resetFields();
    };

    // 根据条件进行搜索
    const handleSearch = (): void => {
      getTableData(formInline);
    };

    // 项目类型
    const initProjectTypeList = async () => {
      try {
        const { data } = await postDictList({ dicType: "thd_pro_role" });
        roleTypeList.value = data || [];
      } catch (err) {
        console.log(err);
      }
    };
    initProjectTypeList();

    // 编辑用户
    const handleEdit = (row): void => {
      state.dialogFormVisible = true;
      state.userInfo = row;
    };

    const showDeleteMessageBox = row => {
      ElMessageBox.confirm("确定删除该条记录吗？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        iconClass: "el-icon-warning"
      })
        .then(() => {
          handleDelete(row);
        })
        .catch(() => {});
    };

    // 删除用户
    const handleDelete = async (item: any) => {
      try {
        const { code, message } = await delProjectTeam({ id: item.id });
        if (code === 200) {
          NotifMessage.success(message);
          getTableData(formInline);
        } else {
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 请求数据
    getTableData(formInline);
    return {
      ...toRefs(state),
      total,
      tableRef,
      formRef,
      loading,
      formInline,
      roleTypeList,
      handleReset,
      handleSearch,
      handleEdit,
      handleDelete,
      emitClose,
      emitAddUser,
      showDeleteMessageBox
    };
  }
});
</script>
<style>
.el-icon-warning {
  color: #e45d5d !important;
}
</style>
<style lang="scss" scoped>
.content-table :deep .el-dialog .form__footer {
  text-align: right;
}
</style>
